@extends('layouts.base')

@section('body_class', 'app-body')

@section('content')
<div class="screen">
    @yield('main-content')

    <!-- 底部导航 -->
    <div class="bottom-nav">
        <div class="nav-item {{ request()->routeIs('home*') ? 'active' : '' }}" data-page="{{ route('home') }}">
            <div class="nav-icon">🏠</div>
            <div>首页</div>
        </div>
        <a href="{{ route('statistics.index') }}" class="nav-item {{ request()->routeIs('statistics.*') ? 'active' : '' }}">
            <div class="nav-icon">📊</div>
            <div>统计</div>
        </a>
        <div class="nav-item" id="quick-record-btn">
            <div class="nav-icon" style="font-size: 24px;">➕</div>
            <div>记账</div>
        </div>
        <a href="{{ route('details.index') }}" class="nav-item {{ request()->routeIs('details.*') ? 'active' : '' }}">
            <div class="nav-icon">📝</div>
            <div>明细</div>
        </a>
        <div class="nav-item {{ request()->routeIs('user.*') ? 'active' : '' }}" data-page="{{ route('user.profile') }}">
            <div class="nav-icon">👤</div>
            <div>我的</div>
        </div>
    </div>
</div>

<!-- 一句话记账弹窗 -->
<div class="quick-record" id="quick-record-modal">
    @csrf
    <div class="quick-record-header">
        <div class="quick-record-title">一句话记账</div>
        <div class="close-btn" id="close-quick-record">✕</div>
    </div>
    <div class="voice-input">
        <input type="text" class="voice-input-field" id="voice-input-field" placeholder="例如：今天午餐花了30元">
        <div class="mic-btn" id="mic-btn">🎤</div>
    </div>

    <!-- 截图上传区域 -->
    <div class="image-upload-section">
        <div class="upload-divider">
            <span>或</span>
        </div>
        <div class="image-upload-area">
            <form id="image-upload-form" enctype="multipart/form-data">
                <input type="file" name="image" id="image-input" accept="image/*" style="display: none;">
            </form>
            <div class="upload-placeholder" id="upload-placeholder">
                <div class="upload-icon">📷</div>
                <div class="upload-text">点击上传截图</div>
                <div class="upload-hint">支持JPG、PNG格式</div>
            </div>
            <div class="image-preview" id="image-preview" style="display: none;">
                <img id="preview-img" src="" alt="预览图片">
                <div class="image-actions">
                    <button type="button" class="btn-icon" id="delete-image" title="删除图片">🗑️</button>
                    <button type="button" class="btn-icon" id="reselect-image" title="重新选择">🔄</button>
                </div>
            </div>
        </div>
    </div>

    <button class="btn btn-primary" id="submit-quick-record">AI识别</button>
</div>

<!-- 识别结果模态框 -->
<div class="modal fade" id="aiResultModal" tabindex="-1" aria-labelledby="aiResultModalLabel" style="display: none;">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header" style="margin-bottom: 0">
                <h5 class="modal-title" id="aiResultModalLabel">识别结果</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="ai-result">
                    <div class="result-item">
                        <span class="label">类型：</span>
                        <span class="value" id="resultType"></span>
                    </div>
                    <div class="result-item">
                        <span class="label">金额：</span>
                        <span class="value" id="resultAmount"></span>
                    </div>
                    <div class="result-item">
                        <span class="label">分类：</span>
                        <span class="value" id="resultCategory"></span>
                    </div>
                    <div class="result-item">
                        <span class="label">日期：</span>
                        <span class="value" id="resultDate"></span>
                    </div>
                    <div class="result-item">
                        <span class="label">备注：</span>
                        <span class="value" id="resultDescription"></span>
                    </div>
                </div>
            </div>
            <div class="modal-footer" style="margin-top: 0">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-success" id="saveTransaction">保存</button>
                <button type="button" class="btn btn-primary" id="editTransaction">编辑</button>
            </div>
        </div>
    </div>
</div>

<!-- 遮罩层 -->
<div class="overlay" id="overlay"></div>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    // 底部导航点击事件
    $('.nav-item[data-page]').on('click', function() {
        const page = $(this).data('page');
        if (page && page !== '#') {
            window.location.href = page;
        }
    });

    // 一句话记账功能
    $('#quick-record-btn').on('click', function() {
        $('#quick-record-modal').addClass('active');
        $('#overlay').addClass('active');
    });

    $('#close-quick-record, #overlay').on('click', function() {
        $('#quick-record-modal').removeClass('active');
        $('#overlay').removeClass('active');
    });

    // 麦克风按钮点击事件
    $('#mic-btn').on('click', function() {
        // 模拟语音识别
        const inputText = $('#voice-input-field').val().trim();
        if (!inputText) showToast('请使用输入法语音转文字或者打字输入');
        else {
            $('#submit-quick-record').click()
        }
        // setTimeout(() => {
        //     $('#voice-input-field').val('今天午餐花了45元');
        // }, 1500);
    });

    /*// 语音录制相关变量
    let mediaRecorder;
    let audioChunks = [];
    let isRecording = false;
    let audioBlob = null;

    // 麦克风按钮点击事件
    $('#mic-btn').on('click', function() {
        if (!isRecording) {
            // 开始录音
            startRecording();
        } else {
            // 停止录音
            stopRecording();
        }
    });

    // 开始录音函数
    function startRecording() {
        // 检查浏览器是否支持MediaRecorder
        if (!navigator.mediaDevices || !window.MediaRecorder) {
            showToast('您的浏览器不支持录音功能，请使用Chrome、Firefox或Edge浏览器', 'error');
            return;
        }

        // 请求麦克风权限
        navigator.mediaDevices.getUserMedia({ audio: true })
            .then(stream => {
                // 显示正在录音的状态
                isRecording = true;
                $('#mic-btn').text('🔴');
                $('#mic-btn').css('background', 'linear-gradient(135deg, #ff4b4b 0%, #ff9b4b 100%)');
                showToast('正在录音...请说出您要记录的账单信息');

                // 创建MediaRecorder实例
                mediaRecorder = new MediaRecorder(stream);
                audioChunks = [];

                // 收集录音数据
                mediaRecorder.ondataavailable = (event) => {
                    if (event.data.size > 0) {
                        audioChunks.push(event.data);
                    }
                };

                // 录音结束后的处理
                mediaRecorder.onstop = () => {
                    // 关闭麦克风
                    stream.getTracks().forEach(track => track.stop());

                    // 创建音频Blob
                    audioBlob = new Blob(audioChunks, { type: 'audio/webm' });

                    // 上传音频文件
                    uploadAudioFile(audioBlob);
                };

                // 开始录音
                mediaRecorder.start();

                // 设置最长录音时间（10秒）
                setTimeout(() => {
                    if (isRecording) {
                        stopRecording();
                    }
                }, 10000);
            })
            .catch(error => {
                console.error('获取麦克风权限失败:', error);
                showToast('无法访问麦克风，请确保已授予麦克风权限', 'error');
            });
    }

    // 停止录音函数
    function stopRecording() {
        if (mediaRecorder && isRecording) {
            isRecording = false;
            $('#mic-btn').text('🎤');
            $('#mic-btn').css('background', 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)');
            mediaRecorder.stop();
            showToast('录音已完成，正在处理...');
        }
    }

    // 上传音频文件函数
    function uploadAudioFile(blob) {
        const formData = new FormData();
        formData.append('_token', $('input[name="_token"]').val());
        formData.append('audio', blob, 'recording.webm');

        showToast('正在上传并解析语音...');

        $.ajax({
            url: '{{ route("transaction.storeByAi") }}',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    // 关闭一句话记账弹窗
                    $('#quick-record-modal').removeClass('active');
                    $('#overlay').removeClass('active');

                    // 清空输入和图片
                    $('#voice-input-field').val('');
                    if (selectedImage) {
                        selectedImage = null;
                        $('#image-input').val('');
                        $('#upload-placeholder').show();
                        $('#image-preview').hide();
                        $('#preview-img').attr('src', '');
                    }

                    // 获取识别结果数据
                    showAiResult(response);
                } else {
                    showError(response.message || '语音识别失败，请重试');
                }
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    let errorMessage = '验证失败：\n';
                    for (let field in errors) {
                        errorMessage += errors[field].join('\n') + '\n';
                    }
                    showError(errorMessage);
                } else {
                    showError(xhr.responseJSON.message || '语音识别失败，请重试');
                }
            }
        });
    }*/

    // 图片上传功能
    let selectedImage = null;
    const imageInput = document.getElementById('image-input');

    if (imageInput) {
// 直接处理文件选择
        function handleFileSelect() {
            imageInput.click();
        }

        // 点击上传区域
        $('.image-upload-area').on('click', function(e) {
            // 如果点击的是按钮区域，不处理
            if ($(e.target).closest('.image-actions').length > 0) {
                return;
            }
            // 如果没有选择图片，打开文件选择
            if (!selectedImage) {
                handleFileSelect();
            }
        });

        // 文件选择变化处理
        document.getElementById('image-input').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    showToast('请选择图片文件', 'error');
                    return;
                }

                // 验证文件大小（限制为5MB）
                if (file.size > 5 * 1024 * 1024) {
                    showToast('图片大小不能超过5MB');
                    return;
                }

                selectedImage = file;

                // 显示预览
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('preview-img').src = e.target.result;
                    document.getElementById('upload-placeholder').style.display = 'none';
                    document.getElementById('image-preview').style.display = 'block';
                };
                reader.readAsDataURL(file);
            }
        });

        // 删除图片
        document.getElementById('delete-image').addEventListener('click', function(e) {
            e.stopPropagation();
            selectedImage = null;
            document.getElementById('image-input').value = '';
            document.getElementById('upload-placeholder').style.display = 'block';
            document.getElementById('image-preview').style.display = 'none';
            document.getElementById('preview-img').src = '';
        });

        // 重新选择图片
        document.getElementById('reselect-image').addEventListener('click', function(e) {
            e.stopPropagation();
            handleFileSelect();
        });
    }

    // 提交一句话记账
    $('#submit-quick-record').on('click', function() {
        const inputText = $('#voice-input-field').val().trim();

        // 检查是否有输入内容或上传图片
        if (!inputText && !selectedImage) {
            showAlert('请输入记账内容或上传截图');
            return;
        }

        const formData = new FormData();
        formData.append('_token', $('input[name="_token"]').val());
        formData.append('text', inputText);

        if (selectedImage) {
            formData.append('image', selectedImage);
        }

        showToast('正在解析信息...');

        $.ajax({
            url: '{{ route("transaction.storeByAi") }}',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    // 关闭一句话记账弹窗
                    $('#quick-record-modal').removeClass('active');
                    $('#overlay').removeClass('active');

                    // 清空输入和图片
                    $('#voice-input-field').val('');
                    if (selectedImage) {
                        selectedImage = null;
                        $('#image-input').val('');
                        $('#upload-placeholder').show();
                        $('#image-preview').hide();
                        $('#preview-img').attr('src', '');
                    }

                    showAiResult(response);
                } else {
                    showError(response.message || '识别失败，请重试', response);
                }
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    let errorMessage = '验证失败：\n';
                    for (let field in errors) {
                        errorMessage += errors[field].join('\n') + '\n';
                    }
                    showError(errorMessage);
                } else {
                    // 直接传入整个response对象作为options
                    const response = xhr.responseJSON || {};
                    showError(response.message || '识别失败，请重试', response);
                }
            }
        });
    });

    function showAiResult(response) {
        // 获取识别结果数据
        var data = response.data.data.res;

        // 更新模态框内容
        $('#resultType').text(data.type === 'expense' ? '支出' : '收入');
        $('#resultAmount').text('¥' + data.amount);
        $('#resultCategory').text(data.category);
        $('#resultDate').text(data.date);
        $('#resultDescription').text(data.description || '');

        // 存储当前数据用于后续操作
        $('#aiResultModal').data('transaction-data', response.data.key);

        // 显示模态框
        var resultModal = new bootstrap.Modal(document.getElementById('aiResultModal'));
        resultModal.show();
    }

    // 处理直接保存
    $('#saveTransaction').on('click', function() {
        const ai_key = $('#aiResultModal').data('transaction-data');
        $.ajax({
            url: '{{ route("transaction.store") }}',
            method: 'POST',
            data: {
                _token: $('input[name="_token"]').val(),
                'ai_key': ai_key,
            },
            success: function(response) {
                if (response.success) {
                    showSuccess('保存成功');
                    // 关闭模态框
                    bootstrap.Modal.getInstance(document.getElementById('aiResultModal')).hide();
                    // 刷新页面
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                } else {
                    showError(response.message || '保存失败', response);
                }
            },
            error: function(xhr) {
                // 直接传入整个response对象作为options
                const response = xhr.responseJSON || {};
                showError(response.message || '保存失败，请重试', response);
            }
        });
    });

    // 处理进入编辑
    $('#editTransaction').on('click', function() {
        const data = $('#aiResultModal').data('transaction-data');
        window.location.href = '{{ route('transaction.create') }}?ai_key=' + data;
    });
});
</script>
@endpush

@push('styles')
<style>
/* 应用主体样式 */
.app-body {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.screen {
    max-width: 414px;
    margin: 0 auto;
    background: white;
    min-height: 100vh;
    position: relative;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

/* 快速记账弹窗样式 */
.quick-record {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    border-radius: 24px 24px 0 0;
    padding: 30px 20px 30px 20px;
    box-shadow: 0 -10px 30px rgba(0,0,0,0.1);
    z-index: 2000;
    transform: translateY(100%);
    transition: transform 0.3s ease;
}

.quick-record.active {
    transform: translateY(0);
}

.quick-record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.quick-record-title {
    font-size: 18px;
    font-weight: 600;
    color: #2d3748;
}

.close-btn {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: #e2e8f0;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.voice-input {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.voice-input-field {
    flex: 1;
    padding: 15px;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    font-size: 16px;
}

.mic-btn {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.mic-btn:hover {
    transform: scale(1.05);
}

/* 图片上传样式 */
.image-upload-section {
    margin-bottom: 20px;
}

.upload-divider {
    text-align: center;
    margin: 15px 0;
    position: relative;
}

.upload-divider::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 1px;
    background: #e2e8f0;
    z-index: 1;
}

.upload-divider span {
    background: white;
    padding: 0 15px;
    color: #718096;
    font-size: 14px;
    position: relative;
    z-index: 2;
}

.image-upload-area {
    border: 2px dashed #e2e8f0;
    border-radius: 12px;
    padding: 20px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s ease;
}

.image-upload-area:hover {
    border-color: #667eea;
    background: #f8fafc;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
}

.upload-icon {
    font-size: 32px;
    opacity: 0.6;
}

.upload-text {
    font-size: 16px;
    color: #4a5568;
    font-weight: 500;
}

.upload-hint {
    font-size: 12px;
    color: #718096;
}

.image-preview {
    position: relative;
}

.image-preview img {
    max-width: 100%;
    max-height: 200px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.image-actions {
    position: absolute;
    top: 8px;
    right: 8px;
    display: flex;
    gap: 8px;
}

.btn-icon {
    width: 32px;
    height: 32px;
    border: none;
    border-radius: 50%;
    background: rgba(0,0,0,0.6);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s ease;
}

.btn-icon:hover {
    background: rgba(0,0,0,0.8);
    transform: scale(1.1);
}

.btn {
    width: 100%;
    padding: 12px;
    border: none;
    border-radius: 12px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 遮罩层样式 */
.overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1005;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
}

.overlay.active {
    opacity: 1;
    visibility: visible;
}

/* 响应式设计 */
@media (max-width: 414px) {
    .screen {
        width: 100%;
        box-shadow: none;
    }

    .bottom-nav {
        width: 100%;
    }
}

/* AI识别结果弹窗样式 */
.ai-result {
    text-align: left;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
    margin: 10px 0;
}

.result-item {
    margin: 10px 0;
    display: flex;
    align-items: center;
}

.result-item .label {
    color: #666;
    width: 60px;
    flex-shrink: 0;
}

.result-item .value {
    color: #333;
    font-weight: 500;
    flex: 1;
}

/* 自定义模态框样式 */
.modal-content {
    border-radius: 16px;
    border: none;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}

.modal-header {
    border-bottom: 1px solid #edf2f7;
    padding: 20px;
}

.modal-title {
    font-size: 18px;
    font-weight: 600;
    color: #2d3748;
}

.modal-body {
    padding: 20px;
}

.modal-footer {
    border-top: 1px solid #edf2f7;
    padding: 15px 20px;
    display: flex;
    justify-content: space-between;
    gap: 10px;
}

.modal-footer .btn {
    padding: 8px 0;
    border-radius: 8px;
    font-weight: 500;
    flex: 1;
    text-align: center;
}

.modal-footer .btn-secondary {
    background-color: #e2e8f0;
    border-color: #e2e8f0;
    color: #4a5568;
}

.modal-footer .btn-secondary:hover {
    background-color: #cbd5e0;
    border-color: #cbd5e0;
}

.modal-footer .btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
}

.modal-footer .btn-success {
    background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
    border: none;
}

.modal-dialog-centered {
    display: flex;
    align-items: center;
    min-height: calc(100% - 1rem);
}

@media (max-width: 414px) {
    .modal-dialog {
        margin: 0.5rem;
    }

    .modal-footer {
        padding: 15px;
    }

    .modal-footer .btn {
        font-size: 14px;
        padding: 8px 0;
    }
}
</style>
@endpush
